//
//  NSWindow+Style.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/10.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

enum WindowStyle {
    case none
    case onlyClose
}

extension NSWindow {
    
    /*
     默认没有最大化按钮，其他都是有
     */
    func setDefault() {
        self.collectionBehavior = NSWindow.CollectionBehavior.fullScreenNone
        
        //设置圆角
        self.contentView?.layer?.masksToBounds = true
        self.contentView?.layer?.cornerRadius = 5
        self.contentView?.wantsLayer = true
        self.backgroundColor = NSColor.clear
        
        self.level = NSWindow.Level.normal
        //self.animationBehavior = .alertPanel
        
        self.backingType = .buffered
        self.isMovableByWindowBackground = true
        self.hasShadow = true
        //self.titlebarAppearsTransparent = true
        //self.titleVisibility = .hidden
        self.isMovable = true
        self.title = ""
        self.styleMask = [.titled,.closable,.miniaturizable]
        self.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
    }
    
    /*
     全屏共享用到
     */
    func setScreen() {
        self.collectionBehavior = [.fullScreenAuxiliary]    //.canJoinAllSpaces
        self.isOpaque = false
        self.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.mainMenuWindow))+1)
        if #available(macOS 10.15, *) {
            self.styleMask = [.fullSizeContentView]
        }else {
            self.styleMask = [.fullScreen]
        }
        self.backingType = .buffered
        self.backgroundColor = NSColor.clear
        //锁定窗口位置
        self.isMovable = false
        
        /*
        //基于x文档的程序
        self.windowController?.shouldCascadeWindows = false
        self.saveFrame(usingName: self.representedFilename)
        
        //自定记忆和恢复位置
        self.setFrameAutosaveName(NSWindow.FrameAutosaveName.init("Positon"))
        //手动恢复位置
        self.setFrameUsingName(NSWindow.FrameAutosaveName.init("some name"))
        //如果是手动保存，则需要手动恢复
        self.setFrameAutosaveName(NSWindow.FrameAutosaveName.init("some name"))
        //清除记忆的位置
        NSWindow.removeFrame(usingName: NSWindow.FrameAutosaveName.init("some name"))
        */
    }
    
    /*
    没有导航
    */
    func setNoTabar() {
        self.styleMask = [.fullSizeContentView]
        
        //设置圆角
        //self.contentView?.wantsLayer = true
        //self.backgroundColor = NSColor.clear
        //self.isOpaque = false
        
        //未锁定移动
        self.isMovable = true
        self.isMovableByWindowBackground = true
        
        self.titlebarAppearsTransparent = true
        self.titleVisibility = .hidden
        
        self.standardWindowButton(.closeButton)?.isHidden = true
        self.standardWindowButton(.zoomButton)?.isHidden = true
        self.standardWindowButton(.miniaturizeButton)?.isHidden = true
    }
    
    /*
     没有导航
     */
    func setNoTabarAndMask() {
        
        //设置圆角
        //self.contentView?.wantsLayer = true
        //self.backgroundColor = NSColor.clear
        //self.isOpaque = false
        
        if #available(macOS 10.15, *) {
            self.styleMask = [.fullSizeContentView]
        }else {
            self.styleMask = [.fullScreen]
        }
        
        //未锁定移动
        self.isMovable = true
        self.isMovableByWindowBackground = true
        
        self.titlebarAppearsTransparent = true
        self.titleVisibility = .hidden
        
        self.standardWindowButton(.closeButton)?.isHidden = true
        self.standardWindowButton(.zoomButton)?.isHidden = true
        self.standardWindowButton(.miniaturizeButton)?.isHidden = true
    }
    
    /*
     导航和背景都没有
     */
    func setNoBackground() {
        self.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.dockWindow))+1)
        if #available(macOS 10.15, *) {
            self.styleMask = [.fullSizeContentView]
        }else {
            self.styleMask = [.fullScreen]
        }
        self.backgroundColor = NSColor.clear
        self.isOpaque = false
        
        //未锁定移动
        self.isMovable = true
        self.isMovableByWindowBackground = true

        self.titlebarAppearsTransparent = true
        self.titleVisibility = .hidden
        self.toolbar?.showsBaselineSeparator = false

        self.standardWindowButton(.closeButton)?.isHidden = true
        self.standardWindowButton(.zoomButton)?.isHidden = true
        self.standardWindowButton(.miniaturizeButton)?.isHidden = true
    }
    
    convenience init(contentRect: CGRect, style: WindowStyle) {
        switch style {
        case .none:
            let styleMask: NSWindow.StyleMask = [.titled, .fullSizeContentView]
            self.init(contentRect: contentRect, styleMask: styleMask, backing: .buffered, defer: true)
            self.titlebarAppearsTransparent = true
            self.titleVisibility = .hidden
            self.toolbar?.showsBaselineSeparator = false

            self.styleMask.insert(.fullSizeContentView)

            self.standardWindowButton(.closeButton)?.isHidden = true
            self.standardWindowButton(.zoomButton)?.isHidden = true
            self.standardWindowButton(.miniaturizeButton)?.isHidden = true
        case .onlyClose:
            let styleMask: NSWindow.StyleMask = [.titled, .fullSizeContentView]
            self.init(contentRect: contentRect, styleMask: styleMask, backing: .buffered, defer: true)
            self.titlebarAppearsTransparent = true
            self.titleVisibility = .hidden
            self.toolbar?.showsBaselineSeparator = false

            self.styleMask.insert(.fullSizeContentView)

            self.standardWindowButton(.zoomButton)?.isHidden = true
            self.standardWindowButton(.miniaturizeButton)?.isHidden = true
      }
        
    }

}

enum FrameDirection {
    case left
    case right
    case top
    case bottom
}

extension NSWindow {
    func direction(in:FrameDirection = .top) {
        var frame = self.frame
        switch `in` {
        case .left:
            frame.origin.x = 0
        case .right:
            frame.origin.x = KSCREENWIDTH-frame.size.width
        case .top:
            frame.origin.y = KSCREENHEIGHT-frame.size.height
        case .bottom:
            frame.origin.y = 0
        }
        self.setFrame(frame, display: true)
    }
    
    
    class func getCenterRect(from:NSRect,to rect:NSRect) -> NSRect {
        let point = NSWindow.getCenterOrigin(from: from, to: rect)
        let newRect = NSRect.init(origin: point, size: rect.size)
        return newRect
    }
    
    @discardableResult
    class func getCenterOrigin(from:NSRect,to:NSRect) -> NSPoint {
        let left = (from.width-to.width)/2
        let top = (from.height-to.height)/2
        var origin = from.origin
        origin.x+=left
        origin.y+=top
        return origin
    }
    
    func setCenter(supWindow:NSWindow, toRect:NSRect, animate:Bool) {
        let center = NSWindow.getCenterOrigin(from: supWindow.frame, to: toRect)
        self.setFrame(NSRect.init(origin: center, size: toRect.size), display: true, animate: animate)
    }
}

extension NSWindow {
    private struct Keys {
        static var bg_key = "bg_key"
    }

    private class Weak<V: AnyObject> {
        weak var value: V?
        init?(_ value: V?) {
            guard value != nil else { return nil }
            self.value = value
        }
    }

    var bg: MdView? {
        get {
            (objc_getAssociatedObject(self, &Keys.bg_key) as? Weak<MdView>)?.value
        }
        set {
            objc_setAssociatedObject(self, &Keys.bg_key, Weak(newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func addBgCover() {
        let view = MdView.init()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(255).withAlphaComponent(1).cgColor
        self.contentView?.addSubview(view)
        self.bg = view
        view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    func removeBgCover() {
        if self.bg != nil {
            self.bg!.removeFromSuperview()
        }
    }
}


extension NSWindow {
    func ga_childWindow(cls:AnyClass) -> NSWindow? {
        if let childWindows = self.childWindows {
            for (_,window) in childWindows.enumerated() {
                if window.contentViewController?.isKind(of: cls) == true {
                    return window
                }
            }
        }
        return nil
    }
}
